#!/bin/sh

#============version 0.9============
#函数化
#增加tomcat检测
#===========v1.3
#tomcat心跳
##################
#===========v1.4
#tomcat心跳判断兼容新老url
#修正语法错误

baseDir="/opt/app/server" 
VerSion=1.00
logfile=$3

function Setlog(){
    echo $1 >> $logfile
}

function SetStatus(){
    sid=$1
    LocalIP=`/sbin/ifconfig |grep "inet addr" |awk '{print $2}' |awk -F : '{print $2}' | grep -v '127.0.0.1'`
    curl -s -m 2 http://cmdb.com/blapp/srelease/?sid=$sid\&appip=$LocalIP\&appport=$tomcatPort\&operation=fabu-sit
    if [ $? -eq 0 ];then
        case $sid in
            1)
                echo "cmdb状态已更新为: 发布成功"
            ;;
            2)
                echo "cmdb状态已更新为: 发布中"
            ;;
            3)
                echo "cmdb状态已更新为: 发布失败"
            ;;
            *)
                echo "参数传入错误,请检查!!!"
        esac
    else
        echo "cmdb 修改失败,请检查!!!"
    fi
    echo ""
}



function PortsCheck()
{
tomcatPort=`grep ^$1\= /opt/app/appPorts.properties | cut -d = -f2`
if	[ ! $tomcatPort  ]
	then     
		echo "    |--->[×]获取${1}端口失败,请检查传参！本次发布被取消！无需回滚 "
		exit 1
	else				
		echo "    |--->[√]启动端口号是:${tomcatPort}"
		serverName="apache-tomcat-$tomcatPort"
		echo "    |--->[√]tomcat目录:${serverName}"
fi
echo ""
}

function PortStatus()
{
nc -v -w 10 -z 127.0.0.1 $tomcatPort > /dev/null
if
    [ $? != 0 ]
    then
        Setlog "    |--->[?]"$1"服务正在启动...."
        sleep 10
        nc -v -w 10 -z 127.0.0.1 $tomcatPort > /dev/null
            if [ $? != 0 ]
                then
                    Setlog "    |--->[×]"$1"服务端口离线...."
                    echo "    |--->[×]"$1"服务端口离线...."
                    SetStatus 3
                else
                    Setlog "    |--->[√]"$1"服务端口在线"
                    echo "    |--->[√]"$1"服务端口在线"
                    SetStatus 1
            fi
    else
        echo "    |--->[√]"$1"服务端口在线"
        Setlog "    |--->[√]"$1"服务端口在线"
        SetStatus 1
fi
}

function ServiceStatus()
{
#http://127.0.0.1:28080/group-osp-social/static/bootstrap/2.3.1/js/bootstrap.min.js
HTTP_CODE1=`curl -m 10 -o  /dev/null -s -w "%{http_code}" http://127.0.0.1:${tomcatPort}/${2}/static/bootstrap/2.3.1/js/bootstrap.min.js`
HTTP_CODE2=`curl -m 10 -o  /dev/null -s -w "%{http_code}" http://127.0.0.1:${tomcatPort}/${2}/static/heartBeat`
HTTP_CODE3=`curl -m 10 -o  /dev/null -s -w "%{http_code}" http://127.0.0.1:${tomcatPort}/${2}/heart/getHeartStatus.html`
if [ x$HTTP_CODE1 = x200 -o x$HTTP_CODE2 = x200 -o x$HTTP_CODE3 = x200 ]
    then
        	echo    "    |--->[√]${1}应用访问正常"
            Setlog  "    |--->[√]${1}应用访问正常"
	else
		echo  "    |--->[×]${1}应用访问异常,请查看日志"
        Setlog  "    |--->[×]${1}应用访问异常,请查看日志"
fi
echo ""
}


echo "---->2.1 获取端口...."
Setlog "---->2.1 获取端口...."
PortsCheck $1

echo "---->2.2 开始检测${1}服务端口状态"
Setlog "---->2.2 开始检测${1}服务端口状态"
sleep 10
PortStatus $1

echo "---->2.3 开始检测${1}应用访问状态"
Setlog "---->2.3 开始检测${1}应用访问状态"
ServiceStatus $1 $2
